<template>
  <j-modal title="产品选择" :width="1200" :visible.sync="modalVisible" :maskClosable="false" @ok="handleOk">
    <a-form layout="inline">
      <a-row style="margin-bottom: 10px">
        <a-col :span="6">
          <a-form-item label="仓库SKU">
            <a-input placeholder="请输入仓库SKU" v-model="queryParam.skuCode" :maxLength="50"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-form-item label="产品名称">
            <a-input placeholder="请输入产品名称" v-model="queryParam.nameCn" :maxLength="255"></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="6">
          <a-button type="primary" @click="loadData(1)" icon="search">查询</a-button>
          <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
        </a-col>
      </a-row>
      <slot name="hint"></slot>
      <a-row>
        <a-col :span="18">
          <a-table
            bordered
            :columns="modalColumns"
            :data-source="modalTableData"
            rowKey="skuCode"
            :loading="loadingModalTable"
            :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
            :pagination="pagination"
            @change="handleTableChange"
          >
            <template #imgSlot="text, record">
              <a-popover trigger="hover" placement="right">
                <template #content>
                  <div class="popover-preview-box">
                    <img :src="mainImg(record.hzArchiveInfoImgsList)" />
                  </div>
                </template>
                <viewer :images="[mainImg(record.hzArchiveInfoImgsList)]" class="img-box">
                  <img :src="mainImg(record.hzArchiveInfoImgsList)" />
                </viewer>
              </a-popover>
            </template>
            <template #proSlot="text, record">
              <div>{{ record.nameCn }}</div>
              <div>{{ record.hzArchiveInfoOtherList[0].color }}；{{ record.hzArchiveInfoOtherList[0].size }}</div>
            </template>
            <template #statusSlot="text, record">
              <a-tag v-if="record.constituteStatus == 1" color="#108ee9"> 单品 </a-tag>
              <a-tag v-else color="#87d068"> 组合 </a-tag>
            </template>
          </a-table>
        </a-col>
        <a-col :span="6">
          <div style="margin-left: 10px">
            <div style="margin-bottom: 10px; font-weight: bold">已选产品：</div>
            <a-table
              bordered
              :columns="checkColumns"
              :data-source="selectedObjCache"
              rowKey="skuCode"
              :pagination="false"
            >
              <template #nameSlot="text, record">
                <div>{{ record.skuCode }}</div>
                <div>{{ record.productName || record.nameCn }}</div>
                <div>
                  <template v-if="record.colorSize">{{ record.colorSize }}</template>
                  <template v-else-if="record.color && record.size">{{ record.color }}；{{ record.size }}</template>
                  <template v-else>
                    {{ record.hzArchiveInfoOtherList[0].color }}；{{ record.hzArchiveInfoOtherList[0].size }}
                  </template>
                </div>
              </template>
              <span slot="action" slot-scope="text, record, index">
                <a @click="delProduct(index)">删除</a>
              </span>
            </a-table>
          </div>
        </a-col>
      </a-row>
    </a-form>
  </j-modal>
</template>

<script>
import { getAction } from '@/api/manage'

export default {
  props: {
    // 是否显示弹框
    visible: {
      type: Boolean,
      default: false,
    },
    // 默认选择的数据
    defaultData: {
      type: Array,
      default: () => [],
    },
    defaultParam: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      modalVisible: this.visible,
      queryParam: {
        skuCode: '',
        nameCn: '',
      },
      modalTableData: [],
      selectedRowKeys: [],
      selectedObjCache: [], // 还没有提交到表单上的临时的产品集合
      /* 分页参数 */
      pagination: {
        current: 1,
        pageSize: 5,
        pageSizeOptions: ['10', '20', '50'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0,
      },
      loadingModalTable: false,
      modalColumns: [
        {
          title: '图片',
          align: 'center',
          width: 110,
          scopedSlots: { customRender: 'imgSlot' },
        },
        {
          title: '仓库SKU',
          dataIndex: 'skuCode',
          width: 160,
          align: 'center',
        },
        {
          title: '产品信息',
          align: 'left',
          scopedSlots: {
            customRender: 'proSlot',
          },
        },
        {
          title: '组合状态',
          align: 'center',
          width: 80,
          scopedSlots: {
            customRender: 'statusSlot',
          },
        },
        {
          title: '单品规格(cm)',
          width: 120,
          align: 'center',
          customRender(text, record) {
            return (
              record.hzArchiveInfoOtherList[0].len +
              '*' +
              record.hzArchiveInfoOtherList[0].widt +
              '*' +
              record.hzArchiveInfoOtherList[0].heig
            )
          },
        },
        {
          title: '毛重(KG)',
          align: 'center',
          width: 90,
          customRender(text, record) {
            return record.hzArchiveInfoOtherList[0].gw
          },
        },
      ],
      checkColumns: [
        {
          title: '产品信息',
          align: 'left',
          width: 180,
          scopedSlots: {
            customRender: 'nameSlot',
          },
        },
        {
          title: '操作',
          align: 'center',
          width: 70,
          scopedSlots: { customRender: 'action' },
        },
      ],
      url: {
        getArchiveList: '/hzkj-product/product/archive/hzArchiveInfoBasic/choose',
      },
    }
  },
  computed: {
    mainImg() {
      return (list) => {
        if (!list || !list.length) return ''
        return list.find((i2) => i2.izMaster == 1).url
      }
    },
  },
  watch: {
    modalVisible(val) {
      this.$emit('update:visible', val)
    },
  },
  methods: {
    loadData(arg) {
      //加载数据 若传入参数1则加载第一页的内容
      if (arg == 1) {
        this.pagination.current = 1
      }
      this.loadingModalTable = true
      getAction(this.url.getArchiveList, {
        ...this.queryParam,
        pageNo: this.pagination.current,
        pageSize: this.pagination.pageSize,
        ...this.defaultParam,
      })
        .then((res) => {
          if (res.success) {
            this.modalTableData = res.result.records
            this.pagination.total = res.result.total
            // 判断当前列表内容是否有已选中的，有的默认勾上
            this.selectedRowKeys = this.modalTableData
              .filter((i1) => this.selectedObjCache.some((i2) => i2.skuCode == i1.skuCode))
              .map((i) => i.skuCode)
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.loadingModalTable = false
        })
    },
    handleTableChange(pagination) {
      //分页、排序、筛选变化时触发
      this.pagination = pagination
      this.loadData()
    },
    searchReset() {
      this.queryParam = {
        skuCode: '',
        nameCn: '',
      }
      this.loadData(1)
    },
    onSelectChange(keys, objs) {
      this.selectedRowKeys = keys
      // 先筛选出不在当前表格中的缓存产品和在当前表格被选中的产品（优先保留之前的数据，可能有回显数据）
      let newArr = this.selectedObjCache.filter(
        (i) =>
          !this.modalTableData.some((i2) => i.skuCode == i2.skuCode) || objs.some((i2) => i.skuCode == i2.skuCode)
      )
      // 筛选出被选中并且不在当前换成的产品
      let objsFilter = objs.filter((i) => !newArr.some((i2) => i.skuCode == i2.skuCode))
      // 把表格中选中的对象并进缓存中
      this.selectedObjCache = [...newArr, ...objsFilter]
    },
    //删除产品
    delProduct(index) {
      this.selectedObjCache.splice(index, 1)
      this.selectedRowKeys = this.selectedRowKeys.filter((i) => this.selectedObjCache.some((j) => j.skuCode == i))
    },
    // 产品提交
    handleOk() {
      this.$emit('submit', this.selectedObjCache)
      this.modalVisible = false
    },
  },
  created() {
    this.loadData(1)
    this.selectedObjCache = JSON.parse(JSON.stringify(this.defaultData))
  },
}
</script>

<style lang="less" scoped>
.popover-preview-box {
  width: 300px;
  height: 300px;
  position: relative;
  background-color: #fafafa;
  img {
    max-height: 100%;
    max-width: 100%;
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
}
.img-box {
  width: 60px;
  height: 60px;
  margin-right: 10px;
  display: inline-block;
  cursor: pointer;
  position: relative;
  background-color: #fafafa;
  img {
    width: 100%;
    height: 100%;
  }
}
</style>
